package org.example.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 使用自定义realm加入md5 + salt + hash
 */
public class CustomerMD5Realm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 一个用户可以有很多身份, 但是只能有一个主身份
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // System.out.println("身份信息: " + primaryPrincipal);
        // 后面必须要通过身份信息来获取角色信息以及权限信息 比如zhourui有admin 和 user角色
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");
        simpleAuthorizationInfo.addStringPermission("user:*:01");

        return simpleAuthorizationInfo;
    }
    /**
     * 注意数据库里存的是加密之后的结果
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        if("zhourui".equals(principal)){
            // 单纯md5
            // return new SimpleAuthenticationInfo(principal, "e10adc3949ba59abbe56e057f20f883e", this.getName());
            // md5 + salt, param1 用户名, param2 存储的盐加密的密码, param3 盐, param4 realm名称
            // 如果是散列之后的结果, 那么散列次数要在创建credentialsMatcher之后往他里面传
            return new SimpleAuthenticationInfo(principal,
                    "81c97817c4e4db0baa3ebd97ad2afebb",
                    ByteSource.Util.bytes("XO*7ps"), this.getName());
        }
        return null;
    }
}
